<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

/**
 * Description of JoomlaParameters
 *
 * @author chaporgin_a
 */
class VA_Form_Form_Mapper_JoomlaParameters extends VA_Form_Form_Mapper {
  private $source = null;
  /**
   *
   * @param array $source
   * @return VA_Form_Form
   */
  public function FromSource($source) {
//    var_dump($source);exit;
//    echo($_POST['params']['fieldInformation']);exit;
    $this->source = $source;
    $form = new VA_Form_Form();
    $form->setTimeout($this->source['timeout'])
            ->setPostedFormMessage($this->source['posted_form_message'])
            ->setReturnMessage($this->source['return_message'])
            ->setTimeoutMessage($this->source['timeout_message'])
            ->setNewFormMessage($this->source['new_form_message'])
            ->setPostLimit($this->source['post_limit'])
            ->setPostLimitMessage($this->source['post_limit_message'])
            ->setTitle($this->source['title']);
    if(!empty($this->source['check_with_link']))
      $form->setRemoteCheckLink($this->source['check_with_link']);
    $this->prepareFieldsFor($form);
    return $form;
  }
  /**
   * Достает всю нужную информацию из источника и создает нужные поля
   * @param VA_Form_Form $form
   */
  private function prepareFieldsFor(VA_Form_Form $form) {
    foreach($this->source['fieldInformation'] as &$field) {
      /* @var $element VA_Form_FormElement */
      $element;
      switch($field->type) {
        case 'textbox':
          $element = $this->prepareTextbox($field);
          break;
        case 'textarea':
          $element = $this->prepareTextarea($field);
          break;
        case 'button':
          if(strtolower($field->func) == 'submit')
            $element = $this->prepareSubmit($field);
          break;
        case 'radio':
        case 'checkbox':
          $element = $this->prepareChoiceElement($field, $field->type);
          break;
        case 'list':
          $element = $this->prepareSelect($field);
          break;
        case 'securimage':
          $element = $this->prepareCaptcha($field);
          break;
        case 'file':
          $element = $this->prepareFile($field);
          break;
        case 'date':
          $element = $this->prepareDate($field);
          break;
        case 'html':
          $element = $this->prepareHTML($field);
          break;
      }
      var_dump($field);
      if( !empty($field->required))
        $element->addValidator(new VA_Form_Validator_Required());
      if( !empty($field->customErrorMessage))
        $element->setHTMLTagAttribute('title', $field->customErrorMessage, TRUE);
      if( !empty($field->validation)) {
        switch($field->validation) {
          case 'Email':
            $element->addValidator(new VA_Form_Validator_Email());
            break;
          case 'Numeric':
            $element->addValidator(new VA_Form_Validator_Numeric());
            break;
          case 'Other':
            $v = new VA_Form_Validator_Regexp();
            $v->init(array('expression'=>$field->altValidation));
            $element->addValidator($v);
            break;
        }
      }
      if( !empty($field->maxLength)) {
        $v = new VA_Form_Validator_Length();
        $v->init(array('max'=>$field->maxLength));
        $element->addValidator($v);
      }
      $element->setName($field->hash)
              ->setHTMLTagAttribute('class', $field->css);
      if(!empty ($field->lw)) $element->setHTMLTagAttribute('label_width', $field->lw);
      if(!empty ($field->lh)) $element->setHTMLTagAttribute('label_height', $field->lh);
      if(!empty ($field->label)) $element->setLabel($field->label);
      $elementWithNoWidth = ($element instanceof VA_Form_FormElement_Radio);
      if(!$elementWithNoWidth && !empty($field->cw)) $element->setStyle('width', $field->cw.'px');
      $elementWithHeight = ($element instanceof VA_Form_FormElement_Textarea) ||
        ($element instanceof VA_Form_FormElement_Submit) ||
        ($element instanceof VA_Form_FormElement_Button);
      if($elementWithHeight && !empty($field->ch)) $element->setStyle('height', $field->ch.'px');
      $form->addElement($element);
    }

  }
  public function prepareHTML(&$field){
    $element = new VA_Form_FormElement_HtmlBlock();
    $element->setValue(base64_decode($field->htmlValue));
    
    return $element;
  }
  public function prepareDate(&$field){
    $element = new VA_Form_FormElement_Date();
    $element->setMinDate(strtotime($field->startYear.'/01/01'));
    $element->setValue(join('/',explode('-', $field->defaultValue)));
    return $element;
  }

  public function prepareFile(&$field) {
    $element = new VA_Form_FormElement_MultiFile();
    $storage = new VA_Form_File_Storage_LocalFS(array());
    $element->setStorage($storage);
    if(!empty($field->extensions)) {
      $v = new VA_Form_Validator_Extension();
      $v->init(array(
        'extensions' => explode(',', $field->extensions)
        ));
      $element->addValidator($v);
    }
    return $element;
  }

  /**
   *
   * @param stdClass $field
   * @return VA_Form_FormElement_Captcha
   */
  public function prepareCaptcha(&$field) {
    $element = new VA_Form_FormElement_Captcha();
    return $element;
  }

  /**
   *
   * @param stdClass $field
   * @return VA_Form_FormElement_Select
   */
  public function prepareSelect(&$field) {
    $element = new VA_Form_FormElement_Select();
    $options = explode('\n', $field->elements);
    $values = explode(',', $field->defaultValue);
    if($field->multi) $element->setSelectionType(VA_Form_FormElement_Select::TYPE_MULTIPLE);
    else $element->setSelectionType(VA_Form_FormElement_Select::TYPE_SINGLE);
    foreach($options as $title) {
      $element->setOption($title);
      if( in_array($title, $values)) $element->setValueByTitle($title);
    }
    return $element;
  }

  /**
   *
   * @param stdClass $field
   * @return VA_Form_FormElement_Radio
   */
  private function prepareChoiceElement(&$field, $type) {

    if( $type == 'radio') $element = new VA_Form_FormElement_Radio();
    elseif($type == 'checkbox') $element = new VA_Form_FormElement_Checkbox();
    $buttons = explode('\n', $field->elements);
    foreach($buttons as $b) $element->setChoice(trim($b));
    if(!empty($field->defaultValue)) {
      $default = explode(',',$field->defaultValue);
      foreach($default as $t) $element->setDefaultByTitle(trim($t));
    }
    $element->setGroupLayout($field->layout == 'List'?VA_Form_FormElement_Radio::LAYOUT_LIST:VA_Form_FormElement_Radio::LAYOUT_INLINE)
            ->setLabelPosition($field->align == 'Left'?VA_Form_FormElement_Radio::POS_LABEL_RIGHT:VA_Form_FormElement_Radio::POS_LABEL_LEFT);

    return $element;
  }
  /**
   *
   * @return VA_Form_FormElement_Textbox
   */
  private function prepareTextbox(&$field) {
    $element = new VA_Form_FormElement_Textbox();
    $element->setValue($field->defaultValue);
    $element->setHTMLTagAttribute('size', $field->maxLength);
    return $element;
  }
  private function prepareTextarea(&$field) {
    $element = new VA_Form_FormElement_Textarea();
    $element->setValue($field->defaultValue);
    return $element;
  }
  /**
   *
   * @return VA_Form_FormElement_Submit
   */
  private function prepareSubmit(&$field) {
    $element = new VA_Form_FormElement_Submit();
    $element->setValue($field->label);
    return $element;
  }

  public function FromObject(VA_Form_Form $object) {
    throw new Exception('method not implemented');
  }

}

